#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

cpulimit_get() {
	local cfg="$1"
	local enabled limit exename maxpercentage include_children

	config_get_bool enabled "$cfg" enabled 0
	[ "$enabled" -eq 1 ] || return 1

	config_get limit "$cfg" limit
	[ -z "$limit" ] && return 1

	config_get exename "$cfg" exename
	[ -z "$exename" ] && return 1
	exename="$(basename "$exename")"

	maxpercentage="$(cpulimit -h | sed -n 's/.*--limit=.*from 0 to \([0-9]*\).*/\1/p')"
	[ "$limit" -gt 0 ] && [ "$limit" -le "$maxpercentage" ] || return 1

	config_get_bool include_children "$cfg" include_children 0

	procd_open_instance
	procd_set_param command cpulimit
	procd_append_param command -l "$limit"
	procd_append_param command -e "$exename"
	[ "$include_children" -eq 1 ] && procd_append_param command -i
	procd_set_param stderr 1
	procd_set_param nice -20
	procd_set_param respawn
	procd_close_instance
}

start_service() {
	config_load cpulimit
	config_foreach cpulimit_get list
}

service_triggers() {
	procd_add_reload_trigger "cpulimit"
}
